<template>
    <div class="chart-panel"
         @dragover.prevent
         @drop="onDrop">
        <div id="graph-canvas"></div>
    </div>
</template>

<script>
    import G6 from '@antv/g6'
    import NODE_LIST from './data/node-list'
    import initBehavior from './behavior'
    import customNode from './custom-item/node'
    import defaultConfig from './data/config'
    import uniqueId from 'lodash.uniqueid'

    const startNode = Object.assign({
        id: uniqueId(),
        ...NODE_LIST[0]
    })

    export default {
        name: 'chart-panel',

        data () {
            return {
                graph: null
            }
        },

        created () {
            initBehavior(G6)

            this.customItemInit()
        },

        mounted () {
            setTimeout(this.init, 100) // 100ms 延迟，避免 icon 未加载完成
        },

        methods: {
            init () {
                const canvas = document.getElementById('graph-canvas')

                this.graph = new G6.Graph({
                    container: 'graph-canvas',
                    width: canvas.clientWidth,
                    height: canvas.clientHeight,
                    modes: {
                        default: [
                            'drag-canvas', // 拖拽画布
                            'zoom-canvas', // 缩放
                            'drag-node', // 拖拽节点
                            'hover-node',
                            'hover-edge'
                        ],
                        addEdge: ['add-edge']
                    },
                    ...defaultConfig
                })

                // 初始化 添加 一个 开始节点
                this.graph.read({
                    nodes: [startNode]
                })
            },

            customItemInit () {
                customNode.init()
            },

            onDrop (event) {
                const nodeIndex = event.dataTransfer.getData('nodeIndex')

                if (nodeIndex === '') {
                    return
                }

                const nodeItem = NODE_LIST[nodeIndex]
                const { x, y } = this.graph.getCanvasByPoint(event.offsetX, event.offsetY)

                this.graph.add('node', Object.assign({
                    id: uniqueId(),
                    x,
                    y
                }, nodeItem))
            }
        }
    }
</script>

<style lang="scss" scoped>
    .chart-panel {
        #graph-canvas {
            width: 100%;
            height: 100%;
        }
    }
</style>
